package org.tbjd.client.states;

import org.tbjd.client.beans.Resource;
import org.tbjd.client.beans.Task;
import org.tbjd.client.constants.TimeConstants;

public abstract class AbstractTaskDurationState {

	public abstract float getDuration(Task task);

	/**
	 * Formulas : duration = effort / ( (sum of each resource's ratio) * 100)
	 * 
	 * @param newRatio
	 * @return new duration
	 */
	protected float getRatioDuration(Task task) {
		float sumOfRatios = 0;
		if (task.getResources() != null) {
			for (Resource resource : task.getResources()) {
				sumOfRatios += (float) resource.getRatio();
			}
		}

		if (sumOfRatios == 0) {
			return task.getEffort();
		}

		return (task.getEffort() / sumOfRatios) * 100;
	}

	/**
	 * Formulas : Duration = EndDate - BeginDate
	 * 
	 * @param task
	 * @return the duration in hours
	 */
	protected float getDatesDuration(Task task) {
		float newDuration = (task.getEndDate().getTime() - task.getBeginDate().getTime()) / TimeConstants.HOUR_IN_MILLIS;

		// if task has zero or one resource at 100%, then update effort with same value as duration
		if (task.getResources() == null || task.getResources().size() == 0
				|| (task.getResources().size() == 1 && task.getResources().get(0).getRatio() == 100)) {
			task.setEffort(newDuration);
		}
		
		return newDuration;
	}
}
